package handlers

import (
	"GIN-API/internal/models"
	"GIN-API/internal/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// ChannelHandler 定义频道控制器层结构体
type ChannelHandler struct {
	channelService *service.ChannelService
}

// NewChannelHandler 创建频道控制器层实例
func NewChannelHandler(channelService *service.ChannelService) *ChannelHandler {
	return &ChannelHandler{
		channelService: channelService,
	}
}

// CreateChannel 创建频道
func (ch *ChannelHandler) CreateChannel(c *gin.Context) {
	var channel models.Channel
	if err := c.ShouldBindJSON(&channel); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
		return
	}
	if err := ch.channelService.CreateChannel(&channel); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建频道失败"})
		return
	}
	c.JSON(http.StatusCreated, channel)
}

// GetChannelByID 根据频道 ID 获取频道信息
func (ch *ChannelHandler) GetChannelByID(c *gin.Context) {
	id := c.Param("id")
	var channelID uint
	if _, err := fmt.Sscanf(id, "%d", &channelID); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的频道 ID"})
		return
	}
	channel, err := ch.channelService.GetChannelByID(channelID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取频道信息失败"})
		return
	}
	if channel == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "频道不存在"})
		return
	}
	c.JSON(http.StatusOK, channel)
}

// UpdateChannel 更新频道信息
func (ch *ChannelHandler) UpdateChannel(c *gin.Context) {
	id := c.Param("id")
	var channelID uint
	if _, err := fmt.Sscanf(id, "%d", &channelID); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的频道 ID"})
		return
	}
	var updatedChannel models.Channel
	if err := c.ShouldBindJSON(&updatedChannel); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
		return
	}
	updatedChannel.ID = channelID
	if err := ch.channelService.UpdateChannel(&updatedChannel); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新频道信息失败"})
		return
	}
	c.JSON(http.StatusOK, updatedChannel)
}

// DeleteChannel 根据频道 ID 删除频道
func (ch *ChannelHandler) DeleteChannel(c *gin.Context) {
	id := c.Param("id")
	var channelID uint
	if _, err := fmt.Sscanf(id, "%d", &channelID); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的频道 ID"})
		return
	}
	if err := ch.channelService.DeleteChannel(channelID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除频道失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "频道删除成功"})
}

// GetAllChannels 获取所有频道
func (ch *ChannelHandler) GetAllChannels(c *gin.Context) {
	channels, err := ch.channelService.GetAllChannels()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取频道列表失败"})
		return
	}
	c.JSON(http.StatusOK, channels)
}
